# EMA策略
import talib
import module_backtest
from vnctptdType661 import *
from PyQt5 import QtCore
# CTP行情库
from vnctpmd import *
import numpy as np
import globalType
import globalvar

parlist = [['short',3,10,1],['long',10,30,1]]

class MyStrategy(module_backtest.VirtualAccount, QtCore.QThread):
    def __init__(self, period,slippoint):
        super(MyStrategy, self).__init__(period,slippoint)
        self.close = []
        self.type = TradeType_VIRTUALACCOUNT
        '''
        self.period = period
        '''

    def OnKline(self, reportpath1, reportpath2, mddata, arg, strategyname):
        if self.type == TradeType_VIRTUALACCOUNT:
            # 只有量化回测时才做处理，实盘交易不做处理
            super(MyStrategy, self).OnKline(reportpath1, reportpath2, arg, mddata)
        if arg[0]<=0 or arg[1] <=0 :
            return
        # TradingDay = klinedata.TradingDay.decode()
        # klinetime = klinedata.klinetime.decode()
        self.InstrumentID = mddata.InstrumentID.decode()
        # self.exchange=mddata.exchange.decode()
        self.close.append(float(mddata.close))
        try:
            float_close = [float(x) for x in self.close]
        except Exception as e:
            pass
        self.EMA_A = talib.EMA(np.array(float_close), arg[0])
        self.EMA_B = talib.EMA(np.array(float_close), arg[1])
        # print('结果1:' + str(self.EMA5))
        # print('结果2:' + str(self.EMA20))
        if self.EMA_A[len(self.EMA_A) - 1] > self.EMA_B[len(self.EMA_B) - 1]:
            if self.sellvol+self.sellvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Close, VN_OPT_LimitPrice,mddata.close + 1, 1)
            if self.buyvol+self.buyvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Open, VN_OPT_LimitPrice, mddata.close + 1, 1)
        elif self.EMA_A[len(self.EMA_A) - 1] < self.EMA_B[len(self.EMA_B) - 1]:
            if self.buyvol+self.buyvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Close, VN_OPT_LimitPrice, mddata.close - 1, 1)
            if self.sellvol+self.sellvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Open, VN_OPT_LimitPrice, mddata.close - 1, 1)





